<script setup lang="ts">
  import { PropType, ref } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import { useAddType } from '@/services/pages/common/type'

  // 组件属性
  const props = defineProps({
    type: {
      type: String as PropType<'commodity' | 'network' | 'order'>,
      required: true,
    },
    otherParam: {
      type: Object as PropType<{ orderModuleId: string }>,
      default: () => {
        return {
          orderModuleId: '',
        }
      },
    },
  })

  const { form, loading, resetForm, submit } = useAddType(props.type)

  // 弹窗状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 组件事件
  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 表单验证规则
  const rules = ref({
    firstLevel: [{ required: true, message: '请输入父级分类名称', trigger: ['blur', 'change'] }],
    secondLevel: [
      { required: true, message: '请输入二级分类名称', trigger: ['blur', 'change'] },
      {
        validator: (rule, value: string, callback) => {
          let repeatNum = 0
          form.value.childData.forEach((secondLevel) => {
            if (value === secondLevel.name) {
              repeatNum += 1
            }
          })
          if (repeatNum > 1) {
            callback(new Error('二级分类名称不允许重复'))
            return
          }
          callback()
        },
        trigger: ['blur', 'change'],
      },
    ],
    threeLevel: [
      { required: true, message: '请输入三级分类名称', trigger: ['blur', 'change'] },
      {
        validator: (rule, value: string, callback) => {
          for (let i = 0; i < form.value.childData.length; i++) {
            let repeatNum = 0
            form.value.childData[i].childData.forEach((threeLevel) => {
              if (threeLevel.name === value) {
                repeatNum += 1
              }
            })
            if (repeatNum > 1) {
              callback(new Error('三级分类名称不允许重复'))
              return
            }
          }
          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
  })

  // 是否开启二级分类
  const isEnableSecondType = ref(false)

  /**
   * 添加二级分类
   */
  const addSecondType = () => {
    isEnableThreeLevels.value.push(false)
    if (props.type === 'order') {
      form.value.childData.push({
        id: null,
        name: '',
        parentId: null,
        status: false,
        sort: 0,
        childData: [],
      })
      return
    }
    form.value.childData.push({
      id: null,
      name: '',
      parentId: null,
      status: false,
      childData: [],
    })
  }

  /**
   * 删除二级分类
   * @param {Number} index - 二级分类索引
   */
  const handleDelSecondType = (index: number) => {
    form.value.childData.splice(index, 1)
  }

  // 三级分类开启状态列表
  const isEnableThreeLevels = ref<Array<boolean>>([])

  /**
   * 添加三级分类
   * @param {Number} index - 二级分类索引
   */
  const addThreeLevel = (index: number) => {
    if (props.type === 'order') {
      form.value.childData[index].childData.push({
        id: null,
        name: '',
        parentId: null,
        status: false,
        sort: 0,
        childData: [],
      })
      return
    }
    form.value.childData[index].childData.push({
      id: null,
      name: '',
      parentId: null,
      status: false,
      childData: [],
    })
  }

  /**
   * 删除三级分类
   * @param {Number} secondTypeIndex - 二级分类索引
   * @param {Number} threeLevelTypeIndex - 三级分类索引
   */
  const handleDelThreeLevel = (secondTypeIndex: number, threeLevelTypeIndex: number) => {
    form.value.childData[secondTypeIndex].childData.splice(threeLevelTypeIndex, 1)
  }

  // form表单组件实例
  const formRef = ref<FormInstance | null>(null)

  /**
   * 保存事件
   */
  const onSave = async () => {
    if (formRef.value) {
      try {
        await formRef.value.validate()
        const orderModuleId = props.otherParam ? props.otherParam.orderModuleId : ''
        const res = await submit(orderModuleId)
        ElMessage({
          message: res.message,
          type: res.code === 20000 ? 'success' : 'error',
          plain: true,
          showClose: true,
          duration: 5000,
        })
        if (res.code === 20000) {
          visible.value = false
          resetForm()
          emits('update')
        }
      } catch (e) {
        // e
      }
    }
  }

  /**
   * 关闭弹窗
   */
  const closeDialog = () => {
    visible.value = false
    resetForm()
  }

  /**
   * 将工单一级分类的sort字段转为纯数字
   */
  const orderFirstTypeSortToNum = () => {
    if ('sort' in form.value) {
      form.value.sort = Number(form.value.sort.toString().replace(/[^\d]/g, ''))
    }
  }

  /**
   * 将工单二级分类的sort字段转换为纯数字
   * @param {Number} secondTypeIndex - 二级分类索引
   */
  const orderSecondTypeSortToNum = (secondTypeIndex: number) => {
    if ('sort' in form.value) {
      const _sort = form.value.childData[secondTypeIndex].sort.toString()
      form.value.childData[secondTypeIndex].sort = Number(_sort.replace(/[^\d]/g, ''))
    }
  }

  /**
   * 将工单三级分类的sort字段转为纯数字
   * @param {Number} secondTypeIndex - 二级分类索引
   * @param {Number} threeTypeIndex - 三级分类索引
   */
  const orderThreeTypeSortToNum = (secondTypeIndex: number, threeTypeIndex: number) => {
    if ('sort' in form.value) {
      const _sort = form.value.childData[secondTypeIndex].childData[threeTypeIndex].sort
      form.value.childData[secondTypeIndex].childData[threeTypeIndex].sort = Number(
        _sort.toString().replace(/[^\d]/g, ''),
      )
    }
  }
</script>

<template>
  <h-drawer
    v-model="visible"
    title="新增分类"
    :loading="loading"
    :width="['commodity', 'order'].includes(props.type) ? 1000 : 800"
    unit="px"
    @close="closeDialog"
  >
    <el-form
      ref="formRef"
      label-position="top"
      inline-message
      class="modal_form_content"
      :model="form"
    >
      <!-- 请输入父级分类名称 -->
      <el-form-item
        label="父级分类名称"
        prop="name"
        :rules="rules.firstLevel"
        class="parent_type_name"
      >
        <el-input v-model.trim="form.name" placeholder="请输入父级分类名称" />
      </el-form-item>

      <!-- 分类状态 -->
      <el-form-item label="分类状态" class="status_container same_line">
        <div class="content">
          <el-radio-group v-model="form.status">
            <el-radio :value="false">启用</el-radio>
            <el-radio :value="true">禁用</el-radio>
          </el-radio-group>

          <!-- 是否开启二级分类 -->
          <div class="switch_container">
            <div class="title">是否开启二级分类</div>
            <el-switch v-model="isEnableSecondType" size="small" />
            <div class="text">{{ isEnableSecondType ? '开启' : '关闭' }}</div>
          </div>

          <!-- 添加二级分类 -->
          <div class="add_container">
            <h-link v-if="isEnableSecondType" @click="addSecondType">添加二级分类</h-link>
          </div>

          <!-- 工单排序 -->
          <div v-if="props.type === 'order'" class="order-sort">
            <span class="label">工单排序</span>
            <el-input
              v-if="'sort' in form"
              v-model.trim="form.sort"
              placeholder="请输入工单排序"
              @input="orderFirstTypeSortToNum"
            />
          </div>
        </div>
      </el-form-item>

      <!-- 可见类型 -->
      <el-form-item v-if="props.type === 'commodity'" label="可见类型" class="visible-type">
        <el-select
          v-if="'visibilityType' in form"
          v-model="form.visibilityType"
          placeholder="请输入工单排序"
        >
          <el-option :value="1" label="全部可见"></el-option>
          <el-option :value="2" label="部门可见"></el-option>
          <el-option :value="3" label="公司可见"></el-option>
        </el-select>
      </el-form-item>

      <!-- 二级分类 -->
      <div v-if="isEnableSecondType" class="second_level_type_list">
        <div v-if="form.childData.length > 0" class="top_divider_line"></div>
        <div
          v-for="(secondType, secondTypeIndex) in form.childData"
          :key="secondTypeIndex"
          class="second_level_type"
        >
          <el-form-item
            label="二级分类名称"
            :prop="`childData[${secondTypeIndex}][name]`"
            :rules="rules.secondLevel"
            class="second_level_name"
          >
            <div class="child_type_name">
              <el-input v-model.trim="secondType.name" placeholder="请输入二级分类名称" />
              <h-link type="error" :height="28" @click="handleDelSecondType(secondTypeIndex)"
                >删除</h-link
              >
            </div>
          </el-form-item>

          <el-form-item label="分类状态" class="status_container same_line">
            <div class="content">
              <el-radio-group v-model="form.childData[secondTypeIndex].status">
                <el-radio :value="false">启用</el-radio>
                <el-radio :value="true">禁用</el-radio>
              </el-radio-group>

              <div class="switch_container">
                <div class="title">是否开启三级分类</div>
                <el-switch v-model="isEnableThreeLevels[secondTypeIndex]" size="small" />
                <div class="text">{{ isEnableThreeLevels[secondTypeIndex] ? '开启' : '关闭' }}</div>
              </div>

              <div class="add_container">
                <h-link
                  v-if="isEnableThreeLevels[secondTypeIndex]"
                  @click="addThreeLevel(secondTypeIndex)"
                  >添加三级分类</h-link
                >
              </div>

              <div v-if="props.type === 'order'" class="order-sort">
                <span class="label">工单排序</span>
                <el-input
                  v-if="'sort' in form.childData[secondTypeIndex]"
                  v-model.trim="form.childData[secondTypeIndex].sort"
                  placeholder="请输入工单排序"
                  @input="orderSecondTypeSortToNum(secondTypeIndex)"
                />
              </div>
            </div>
          </el-form-item>

          <!--三级分类-->
          <div v-if="isEnableThreeLevels[secondTypeIndex]" class="three_level_type_list">
            <div
              v-for="(threeLevel, threeLevelIndex) in secondType.childData"
              :key="threeLevelIndex"
              class="three_level_type"
            >
              <el-form-item
                label="三级分类名称"
                :prop="`childData[${secondTypeIndex}][childData][${threeLevelIndex}][name]`"
                :rules="rules.threeLevel"
              >
                <div class="child_type_name">
                  <el-input
                    v-model.trim="form.childData[secondTypeIndex].childData[threeLevelIndex].name"
                    placeholder="请输入三级分类名称"
                  />
                  <h-link
                    type="error"
                    :height="28"
                    @click="handleDelThreeLevel(secondTypeIndex, threeLevelIndex)"
                    >删除</h-link
                  >
                </div>
              </el-form-item>

              <el-form-item label="分类状态" class="status_container same_line">
                <div class="content">
                  <el-radio-group
                    v-model="form.childData[secondTypeIndex].childData[threeLevelIndex].status"
                  >
                    <el-radio :value="false">启用</el-radio>
                    <el-radio :value="true">禁用</el-radio>
                  </el-radio-group>

                  <div v-if="props.type === 'order'" class="order-sort">
                    <span class="label">工单排序</span>
                    <el-input
                      v-if="'sort' in form.childData[secondTypeIndex].childData[threeLevelIndex]"
                      v-model.trim="form.childData[secondTypeIndex].childData[threeLevelIndex].sort"
                      placeholder="请输入工单排序"
                      @input="orderThreeTypeSortToNum(secondTypeIndex, threeLevelIndex)"
                    />
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>

          <div v-if="form.childData.length - 1 !== secondTypeIndex" class="divider_line"></div>
        </div>
      </div>
    </el-form>
    <template #footer>
      <HButton is-modal type="primary" @click="onSave">保存</HButton>
      <HButton is-modal @click="closeDialog"> 取消 </HButton>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  :deep(.el-form-item__error) {
    margin: 3px 0 8px 0 !important;
  }

  :deep(.el-switch__core) {
    height: 16px !important;
    border-radius: 16px !important;
  }

  .modal_form_content {
    row-gap: 0;
    padding: 0 48px;

    .second_level_name,
    .status_container,
    .three_level_type_list,
    .parent_type_name,
    .visible-type {
      padding: 0 24px;
      box-sizing: border-box;
    }

    .status_container {
      display: flex !important;
      align-items: flex-start;
      margin-top: 3px !important;

      :deep(.el-form-item__content) {
        .content {
          display: flex;
          align-items: center;

          .switch_container {
            height: 16px;
            margin: 0 12px 0 48px;

            .title {
              margin-right: 2px;
              height: 16px;
              line-height: 16px;
              font-size: 14px;
              color: #606266;
            }

            .el-switch {
              height: 20px !important;
            }

            .text {
              height: 16px;
              line-height: 16px;
              font-size: 14px;
              color: #606266;
            }
          }

          .add_container {
            height: 16px;
            display: flex;
            align-items: center;
          }

          .order-sort {
            margin-left: 48px;
            display: flex;
            column-gap: 7px;

            .label {
              white-space: nowrap;
              height: 16px;
              line-height: 16px;
              color: #606266;
            }

            .el-input {
              .el-input__wrapper {
                height: 16px !important;

                .el-input__inner {
                  height: 16px;
                  line-height: 16px;
                }
              }
            }
          }
        }
      }
    }

    .parent_type_name {
      :deep(.el-input) {
        width: calc(100% - 24px - 5px);
      }
    }

    .visible-type {
      margin-top: 12px !important;

      :deep(.el-select) {
        width: calc(100% - 24px - 5px) !important;
      }
    }

    .second_level_type_list {
      display: flex;
      flex-direction: column;
      row-gap: 12px;
      margin-top: 12px;

      .top_divider_line {
        border-top: 3px solid $primaryColor;
      }

      .second_level_type {
        display: flex;
        flex-direction: column;
        box-sizing: border-box;

        .child_type_name {
          display: flex;
          width: 100%;
          height: 28px;
          column-gap: 4px;

          :deep(.el-input) {
            flex: 1;
          }
        }

        .three_level_type_list {
          margin-top: 12px;
          display: flex;
          flex-direction: column;
          row-gap: 12px;

          .status_container {
            padding: 0;
          }
        }

        .divider_line {
          border-bottom: 1px solid $primaryColor;
          margin-top: 12px;
        }
      }
    }
  }
</style>
